# -*- coding: utf-8 -*-

from sys import *
path.append("DBManager/")
path.append("tools/")
from Ui_MainWindow import *
from PyQt4.QtGui import *
from DBManager import *
from Log import *

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
  def __init__(self, parent=None):
    QtGui.QMainWindow.__init__(self, parent)
    self.setupUi(self)
    self.dbm = None
    self.setCorner(Qt.TopLeftCorner, Qt.LeftDockWidgetArea)
    self.setCorner(Qt.BottomLeftCorner, Qt.LeftDockWidgetArea)
    self.setCorner(Qt.TopRightCorner, Qt.RightDockWidgetArea)
    self.setCorner(Qt.BottomRightCorner, Qt.RightDockWidgetArea)
    QObject.connect(lgdsLog, SIGNAL("put"), 
    self.lgdsLogField.append)
    QObject.connect(sqlLog, SIGNAL("put"), 
    self.sqlLogField.append)
    for log in logs:
      QObject.connect(log, SIGNAL("put"), 
      self.needFocusLog)
    
    QObject.connect(self.logTabWidget, 
    SIGNAL("currentChanged(int)"), self.unFocusLog)
    
  # Menu auto-connect
  def on_menuFile_triggered(self, action):
    if(action.objectName() == "actionQuit"):
      self.close()
    elif(action.objectName() == "actionOpen"):
      self.open()
  
  def needFocusLog(self, text, logName):
    for i in range(len(logs)):
      if(self.logTabWidget.tabText(i) == logName):
	if(self.logTabWidget.currentIndex() != i):
	  self.logTabWidget.setTabIcon(i, QIcon("icons/needFocus.png"))
	  
  def unFocusLog(self, index):
    self.logTabWidget.setTabIcon(index, QIcon())
  
  # open db
  def open(self):
    filename = QFileDialog.getOpenFileName(
      self,
      "Open database file descriptor",
      "./",
      "eXtended Markup Language (*.xml)"
    )
    if(filename != ""):
      self.dbm = DBManager(filename)
      if(self.dbm.isOpen() == True):
	self.actionClose.setEnabled(True)
	self.tabWidgetView.setEnabled(True)
	self.dbm.execQuery("SELECT * FROM news")
    